package me.kuye.jkuye.plugin.activerecord;

import java.beans.FeatureDescriptor;
import java.util.Iterator;

import javax.el.ELContext;
import javax.el.ELResolver;
import javax.servlet.ServletContext;
import javax.servlet.jsp.JspApplicationContext;
import javax.servlet.jsp.JspFactory;

public class ModelRecordElResolver extends ELResolver {
	static JspApplicationContext jspApplicationContext;

	private static boolean isWorking = true;

	@Override
	public Class<?> getCommonPropertyType(ELContext elcontext, Object base) {
		if (!isWorking) {
			return null;
		}
		if (base instanceof Model || base instanceof Record)
			return String.class;
		return null;
	}
	/*
	 *  初始化JSP模板
	 * 
	 * */
	public static void init(ServletContext servletContext) {
		JspApplicationContext jac = JspFactory.getDefaultFactory().getJspApplicationContext(servletContext);
		if (jac != jspApplicationContext) {
			jspApplicationContext = jac;
			jspApplicationContext.addELResolver(new ModelRecordElResolver());
		}
	}

	@Override
	public Class<?> getType(ELContext context, Object base, Object property) {
		if (isWorking == false)
			return null;

		return (base == null) ? null : Object.class;
	}

	@Override
	public Object getValue(ELContext context, Object base, Object property) {
		if (isWorking == false)
			return null;

		if (base instanceof Model) {
			context.setPropertyResolved(true);
			if (property == null)
				return null;
			return ((Model) base).get(property.toString());
		} else if (base instanceof Record) {
			context.setPropertyResolved(true);
			if (property == null)
				return null;
			return ((Record) base).get(property.toString());
		}
		return null;
	}

	@Override
	public boolean isReadOnly(ELContext elcontext, Object base, Object properties) {
		if (isWorking == false)
			return false;

		if (base instanceof Model || base instanceof Record) {
			elcontext.setPropertyResolved(true);
			return false;
		}
		return false;
	}

	@Override
	public void setValue(ELContext context, Object base, Object property, Object value) {
		if (isWorking == false)
			return;

		if (base instanceof Model) {
			context.setPropertyResolved(true);
			if (property == null)
				return;
			try {
				((Model) base).set(property.toString(), value);
			} catch (Exception e) {
				((Model) base).put(property.toString(), value);
			}
		} else if (base instanceof Record) {
			context.setPropertyResolved(true);
			if (property == null)
				return;
			((Record) base).set(property.toString(), value);
		}
	}

	public static void setWorking(boolean isWorking) {
		ModelRecordElResolver.isWorking = isWorking;
	}

	@Override
	public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext elcontext, Object obj) {
		return null;
	}

}
